package cn.itcast.flink.transformation;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author lilulu
 */
/**
 * Flink中流计算DataStream转换算子：keyBy和sum 算子
 * @author xuyuan
 */
public class TransformationKeyByDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> source = env.socketTextStream("node1.itcast.cn", 9999);
        // 3. 数据转换-transformation
        SingleOutputStreamOperator<String> filterData = source.filter(
                new FilterFunction<String>() {
                    @Override
                    public boolean filter(String line) throws Exception {
                        return line.trim().length() > 0;
                    }
                }
        );
        SingleOutputStreamOperator<String> flatMapData = filterData.flatMap(
                new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String line, Collector<String> collector) throws Exception {
                        String[] words = line.trim().split("\\s+");
                        for (String word : words) {
                            collector.collect(word);
                        }
                    }
                }
        );
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapData = flatMapData.map(
                new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String word) throws Exception {
                        return Tuple2.of(word, 1);
                    }
                }
        );
//        按照单词分组，并且组内求和
        /*mapData.keyBy(
                new KeySelector<Tuple2<String, Integer>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                        return stringIntegerTuple2.f0

                    }
                }
        );*/
//        使用Lambda表达式完成聚合统计
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultData = mapData.keyBy(tuple -> tuple.f0).sum(1);
        // 4. 数据终端-sink
        resultData.printToErr();
        // 5. 触发执行-execute
        env.execute("TransformationKeyByDemo");
    }
}